/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Producer_Consumer_V3.java]
 * Creation Date        [04-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_08_thread.producer_consumer;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 生产者消费者模式 3 - 使用Concurrent包
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Producer_Consumer_V3 {

	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 */
	public static void main(String[] args) {
		Warehouse_V3 warehouse = new Warehouse_V3();

		Producer p1 = new Producer(warehouse, 10);
		Producer p2 = new Producer(warehouse, 30);
		Producer p3 = new Producer(warehouse, 20);
		Producer p4 = new Producer(warehouse, 50);
		Producer p5 = new Producer(warehouse, 40);

		Consumer c1 = new Consumer(warehouse, 50);
		Consumer c2 = new Consumer(warehouse, 20);
		Consumer c3 = new Consumer(warehouse, 70);

		c1.start();
		c2.start();
		c3.start();
		p1.start();
		p2.start();
		p3.start();
		p4.start();
		p5.start();
	}
}

/**
 * 仓库
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
class Warehouse_V3 implements Warehouse {

	// 仓库最大储量
	private static final int MAX_SIZE = 100;

	// 仓库的载体
	private LinkedBlockingQueue<String> list = new LinkedBlockingQueue<String>(
			100);

	/**
	 * 生产number个产品
	 * 
	 * @param number
	 * @throws InterruptedException
	 */
	@Override
	public void produce(int number) throws InterruptedException {
		// 如果仓库剩余容量为0
		if (list.size() == MAX_SIZE) {
			System.out.println("[库存量]: " + MAX_SIZE + "\t暂时不能执行生产任务");
		}

		// 生产条件满足情况下, 生产number个产品
		for (int i = 1; i <= number; i++) {
			// 放入产品, 自动阻塞
			list.put("产品" + i);
		}
		System.out.println("[现在储量为]: " + list.size());
	}

	/**
	 * 消费number个产品
	 * 
	 * @param number
	 * @throws InterruptedException
	 */
	@Override
	public void consume(int number) throws InterruptedException {
		// 如果仓库存储量不足
		if (list.size() == 0) {
			System.out.println("[库存量]: " + MAX_SIZE + "\t暂时不能执行消费任务");
		}
		// 消费条件满足情况下, 消费number个产品
		for (int i = 1; i <= number; i++) {
			// 消费产品, 自动阻塞
			list.take();
		}
	}

}